package org.example.expansionpoint.applicationContextInitializer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Map;

@SpringBootApplication
public class TestApplicationContextInitializerApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(TestApplicationContextInitializerApplication.class);
//        application.addInitializers(new FirstApplicationContextInitializer());
//        application.addInitializers(new SecondApplicationContextInitializer());
        application.addInitializers(new ThirdApplicationContextInitializer());
        ConfigurableApplicationContext context = application.run(args);
        ConfigurableEnvironment environment = context.getEnvironment();
        System.out.println(environment.getProperty("1"));
        System.out.println(environment.getProperty("2"));
        System.out.println(environment.getProperty("3"));
        context.close();
    }

    static class FirstApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

        @Override
        public void initialize(ConfigurableApplicationContext context) {
            putProperty(context, "1", "ONE");
        }
    }

    static class SecondApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        @Override
        public void initialize(ConfigurableApplicationContext context) {
            putProperty(context, "2", "TWO");
        }
    }

    static class ThirdApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        @Override
        public void initialize(ConfigurableApplicationContext context) {
            putProperty(context, "3", "THREE");
        }
    }

    private static void putProperty(ConfigurableApplicationContext context, String key, Object value) {
        Map<String, Object> systemProperties = context.getEnvironment().getSystemProperties();
        systemProperties.put(key, value);
    }

}
